package com.smartian.v2.filters;

import com.smartian.v2.AbstractTextParser;
import com.smartian.v2.model.DateTimeNode;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * Created by tianweitong on 2020/4/10.
 */

public class TextParserInterceptorManager {

    static TextParserInterceptorManager instance;
    private final List<FilterInfo> sFilterInfos = new ArrayList<>();

    public static TextParserInterceptorManager getInstance() {
        if (instance == null) {
            instance = new TextParserInterceptorManager();
        }
        return instance;
    }

    public void register(int id, IDateTimeNodeInterceptor filter) {
        FilterInfo info = new FilterInfo();
        info.filter = filter;
        info.id = id;

        sFilterInfos.add(info);
    }

    public void unregister(int id) {
        Iterator<FilterInfo> iterator = sFilterInfos.iterator();
        while (iterator.hasNext()) {
            FilterInfo next = iterator.next();
            if (next.id == id) {
                iterator.remove();
            }
        }
    }

    public static List<DateTimeNode> dispatchIntercept(AbstractTextParser textParser, int repeatType, List<DateTimeNode> dateTimeNodes) {
        if (textParser == null) return dateTimeNodes;
        TextParserInterceptorManager manager = getInstance();
        List<DateTimeNode> list = manager.onIntercept(textParser, repeatType, dateTimeNodes);
        if (list == null) {
            return dateTimeNodes;
        }
        return list;
    }

    private List<DateTimeNode> onIntercept(AbstractTextParser textParser, int repeatType, List<DateTimeNode> dateTimeNodes) {
        if (sFilterInfos.size() == 0) return dateTimeNodes;
        Iterator<FilterInfo> iterator = sFilterInfos.iterator();

        do {
            if (iterator == null || !iterator.hasNext()) break;
            FilterInfo next = iterator.next();
            if (next.filter.isSupportedRepeatType(repeatType)) {
                next.filter.handleOnIntercept(textParser, repeatType, dateTimeNodes);
            }
        } while (iterator.hasNext());
        return dateTimeNodes;
    }
    public static class FilterInfo {
        int id;
        IDateTimeNodeInterceptor filter;
    }

}

